const Controller = require('egg').Controller
/**
 * @Controller 菜单
 */
class menuController extends Controller {
  /**
   * @summary 添加菜单
   * @router post /menu/insert
   ** @request body insertMenu *body
   * @response 200 testResponse
   * @apikey
 */
  async insert() {
    const { ctx,service } = this
    const body = ctx.request.body
    ctx.validate({
      title: { type: 'string'},
      path: { type: 'string' },
      type: {type: 'enum', values: ['link', 'menu'] }
    },body)

    const data = await service.menuService.insert(body)
    ctx.body = {
      code: 200,
      message: '插入成功',
      data
    }
  }

  /**
   修改菜单
 */
  async update() {
    const { ctx,service } = this
    const body = ctx.request.body
    const Menu = ctx.model.Menu
    ctx.validate({
      id: 'string',
      title: 'string',
      path: 'string'
    },body)
    const data = await Menu.findByIdAndUpdate(body.id,body)
    if(!data) {
      ctx.throw(422,'_id不正确')
    }
  
    ctx.body = {
      code: 200,
      message: '修改成功！'
    }
  }

  /**
   * @summary 删除菜单
 */
  async delete() {
    const { ctx,service } = this
    const body = ctx.request.query
    const Menu = ctx.model.Menu
    ctx.validate({
      id: 'string'
    },body)
    const data = await Menu.findById(body.id).populate('mobileMenuImg','link').populate('menuImg','link').populate('seriesImg','link')
    if(!data) {
      ctx.throw(422, '_id不正确')
    }

    data.remove()
    
    if(_data.mobileMenuImg) {
      await ctx.model.File.deleteOne({_id:_data.mobileMenuImg._id})
      service.toolService.deleteDiskFile(_data.mobileMenuImg.link)
    }
    if(_data.menuImg) {
      await ctx.model.File.deleteOne({_id:_data.menuImg._id})
      service.toolService.deleteDiskFile(_data.menuImg.link)
    }
    if(_data.seriesImg) {
      await ctx.model.File.deleteOne({_id:_data.seriesImg._id})
      service.toolService.deleteDiskFile(_data.seriesImg.link)
    }

    ctx.body = {
      code: 200,
      message: '删除成功！'
    }
  }

  /**
   * @summary 查询菜单
 */
  async list() {
    const { ctx,service } = this
    const data = await service.menuService.getList()
    ctx.body = {
      code: 200,
      data
    }
  }
}

module.exports = menuController